//引入axios核心库
import axios from 'axios'
import qsString from 'querystring'
let baseUrl = '/api'
//引入路由配置文件
import router from "../router";

//引入拦截器
//请求拦截
axios.interceptors.request.use(req =>{
  console.log(req, "qingqiu");
  if (req.url == "/api/userlogin") {
    return req;
  } else {
    //全局添加token请求头
    req.headers.authorization = sessionStorage.getItem("userinfo")
      ? JSON.parse(sessionStorage.getItem("userinfo")).token
      : null;
    return req;
  }
})

//响应拦截
axios.interceptors.response.use(res => {
  //全局拦截错误
  if (res.data.msg == "请设置请求头,并携带验证字符串") {
    //没有添加请求头
    //强制它重新登录
    router.push("/login");
  }
  if (res.data.msg == "登录已过期或访问权限受限") {
    //token过期或者失效 要强制跳转到登录
    router.push("/login");
  }
  return res.data
})

//封装请求方式
export const get = (url, params = {}) => {
  return new Promise((resolve, reject) => {
    axios.get(baseUrl+url, {
        params
      })
      .then(res => resolve(res))
      .catch(err => reject(err))
  })

}

export const post = (url, params = {}, isFile = false) => {
  let data = {}
  if (isFile) {
    data = new FormData()
    for (let i in params) {
      data.append(i, params[i])
    }
  } else {
    data = qsString.stringify(params)
  }
  return new Promise((resolve, reject) => {
    axios.post(baseUrl+url, data)
      .then(res => resolve(res))
      .catch(err => reject(err))
  })

}